import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# 尝试修正URL并加载数据集
try:
    url = "https://raw.githubusercontent.com/MicrosoftDocs/mslearn-introduction-to-machine-learning/main/Data/ml-basics/penguins.csv"
    df = pd.read_csv(url)
except Exception as e:
    print(f"无法加载数据集，请检查URL是否正确或网络连接是否稳定。错误信息：{e}")

# 打印数据集的前5行
print(df.head())

# 可视化企鹅种类的分布情况
plt.figure(figsize=(10, 6))
sns.countplot(x='Species', data=df)
plt.title('Distribution of Penguin Species')
plt.show()

# 使用箱型图可视化不同种类企鹅的FlipperLength, CulmenLength和CulmenDepth的分布情况
plt.figure(figsize=(12, 8))
sns.boxplot(data=df, x='Species', y='FlipperLength')
plt.title('Flipper Length Distribution by Species')
plt.show()

sns.boxplot(data=df, x='Species', y='CulmenLength')
plt.title('Culmen Length Distribution by Species')
plt.show()

sns.boxplot(data=df, x='Species', y='CulmenDepth')
plt.title('Culmen Depth Distribution by Species')
plt.show()

# 显示包含缺失值的行
print(df[df.isnull().any(axis=1)])

# 删除包含缺失值的行
df = df.dropna()

# 分离特征和标签
features = df[['CulmenLength', 'CulmenDepth', 'FlipperLength']]
labels = df['Species']

# 分割数据为训练集和测试集，测试集占30%
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.3, random_state=42)

# 创建并训练一个多类别逻辑回归模型
model = LogisticRegression(multi_class='multinomial', solver='lbfgs', max_iter=200)
model.fit(X_train, y_train)

# 预测测试集的标签并计算模型的准确率
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f'Model Accuracy: {accuracy:.2f}')